package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.SparseArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.db.DatabaseHelper;
import com.zline.foodraise.db.dao.CityDao;
import com.zline.foodraise.db.dao.ProvinceDao;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.City;
import com.zline.foodraise.entity.Province;
import com.zline.foodraise.entity.UserBean;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.util.EmojiFilter;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.RegexUtils;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.dialog.LoadingProgressDialog;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ItemSelect;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by heshantao on 15/7/7.
 * 我要开店
 */
@EActivity(R.layout.activity_open_shop)
public class OpenShopActivity extends ZlineActivity {
    private static final String LOG_TAG = OpenShopActivity.class.getSimpleName();
    //标题
    @StringRes(R.string.open_shop)
    String title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    //省会
    @ViewById(R.id.addr_province_spinner)
    Spinner provinceSpinner;
    List<String> provinceList;
    //城市
    @ViewById(R.id.addr_city_spinner)
    Spinner citySpinner;

    //店铺名
    @ViewById(R.id.shop_name_etv)
    EditText shop_name_etv;
    //店铺具体地址
    @ViewById(R.id.shop_detatil_addr_etv)
    EditText shop_detatil_addr_etv;
    //联系人
    @ViewById(R.id.shop_contact_etv)
    EditText shop_contact_etv;
    //电话
    @ViewById(R.id.shop_phone_etv)
    EditText shop_phone_etv;
    //同意协议
    @ViewById(R.id.agreement_iv)
    ImageView agreement_iv;
    //申请开店
    @ViewById(R.id.apply_open_shop_btn)
    Button apply_open_shop_btn;
    //已申请
    @ViewById(R.id.apply_rl)
    RelativeLayout apply_rl;
    //未申请
    @ViewById(R.id.unapply_rl)
    RelativeLayout unapply_rl;
    @ViewById(R.id.apply_status_iv)
    ImageView apply_status_iv;
    @ViewById(R.id.apply_status_tv)
    TextView apply_status_tv;
    @ViewById(R.id.apply_status_hint_tv)
    TextView apply_status_hint_tv;
    @ViewById(R.id.ask_apply_status_btn)
    Button btn;
    List<String> cityList;
    DatabaseHelper helper;
    @Bean
    ProvinceDao provinceDao;
    @Bean
    CityDao cityDao;
    private int provinceId = 1;
    //省份对应城市列表下标
    private int cityIndex = 0;
    //店铺申请状态 状态 0:审核中 1:通过 2:驳回 3:未提交申请
    @Extra
    int shopStatus;
    @Extra
    String rejectReason;
    //是否同意协议
    boolean isAgreement;
    @Pref
    AppPref_ appPref;
    long userId;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    //城市列表
    List<City> list;
    //城市ID
    long cityId;
    @StringRes(R.string.unapplying_hint)
    String unapply_hint;
    @Bean
    NetworkUtil networkUtil;

    @AfterInject
    void doSomeAfterInject() {
        userId = appPref.userId().get();

    }

    @AfterViews
    void doSomeAfterViews() {
        initData();
        initView();
    }

    void initView() {
        title_tv.setText(title);
        if (shopStatus == 3) {
            setProvinceSpinner();
            setCitySpinner();
        } else if (shopStatus == 0) {
            unapply_rl.setVisibility(View.GONE);
            apply_rl.setVisibility(View.VISIBLE);

        } else if (shopStatus == 2) {
            unapply_rl.setVisibility(View.GONE);
            setProvinceSpinner();
            setCitySpinner();
            apply_rl.setVisibility(View.VISIBLE);
            Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.mipmap.unapply);
            apply_status_iv.setImageBitmap(bitmap);
            apply_status_tv.setText(R.string.unapplying);
            apply_status_hint_tv.setText(unapply_hint + rejectReason);
            btn.setText(R.string.apply_again);
        }
    }

    void initData() {
        if (shopStatus != 0) {//除非是审核中否则都加载
            getProvinces();
            getCitys();
        }
    }


    //获得省份列表
    void getProvinces() {
        getHelper();
        provinceDao.setHelper(helper);
        List<Province> list = provinceDao.findAll();
        provinceList = new ArrayList<String>();
        for (Province province : list) {
            provinceList.add(province.getProvinceName());
            LUtil.i(LOG_TAG, "_________getProvince____" + province.getProvinceName());
        }
    }

    //获得城市列表
    void getCitys() {
        getHelper();
        cityDao.setHelper(helper);
        list = cityDao.findCityByProvinceId(provinceId);
        cityList = new ArrayList<String>();
        for (City city : list) {
            cityList.add(city.getCityName());
        }
    }


    //slite 实例
    void getHelper() {
        if (helper == null) {
            helper = OpenHelperManager.getHelper(OpenShopActivity.this, DatabaseHelper.class);
        }
    }

    //设置省会Spinner
    void setProvinceSpinner() {
        if (provinceList == null) {
            return;
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(OpenShopActivity.this, R.layout.addr_spinner_item, provinceList);
        adapter.setDropDownViewResource(R.layout.addr_spinner_drop_down_item);
        setSpinnerDropDownHeight(provinceSpinner);
        provinceSpinner.setAdapter(adapter);
        provinceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LUtil.i(LOG_TAG, "_____点击第几个____province____" + position);
                provinceId = position + 1;
                getCitys();
                setCitySpinner();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }


    //设置省会对应地级市Spinner
    void setCitySpinner() {
        if (cityList == null) {
            return;
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(OpenShopActivity.this, R.layout.addr_spinner_item, cityList);
        adapter.setDropDownViewResource(R.layout.addr_spinner_drop_down_item);
        setSpinnerDropDownHeight(citySpinner);
        citySpinner.setAdapter(adapter);
        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LUtil.i(LOG_TAG, "_____点击第几个_city_______" + position);
                cityIndex = position;

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    //设置Spinner 下拉列表的高度
    void setSpinnerDropDownHeight(Spinner spinner) {
        try {
            Field popup = Spinner.class.getDeclaredField("mPopup");
            popup.setAccessible(true);
            android.widget.ListPopupWindow popupWindow = (android.widget.ListPopupWindow) popup.get(spinner);
            popupWindow.setHeight(500);
        } catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {

        }

    }


    //申请开店
    void applyOpenShop() {
        String shopName = shop_name_etv.getText().toString().trim();
        if (StringUtils.isBlank(shopName) || shopName.length() < 2 || shopName.length() > 30) {
            TUtil.showShort(this, R.string.shop_name_erro);
            return;
        }
        String province = provinceList.get(provinceId - 1);
        String city = cityList.get(cityIndex);
        if (list != null) {
            cityId = list.get(cityIndex).getCityId();
        }

        String detailAddr = shop_detatil_addr_etv.getText().toString().trim();
        if (StringUtils.isBlank(detailAddr) || detailAddr.length() < 5 || shopName.length() > 50) {
            TUtil.showShort(this, R.string.detail_addr_erro);
            return;
        }
        detailAddr = province + city + detailAddr;
        String contact = shop_contact_etv.getText().toString().trim();
        if (StringUtils.isBlank(contact) || contact.length() < 2 || contact.length() > 10) {
            TUtil.showShort(this, R.string.contact_erro);
            return;
        }
        String mobile = shop_phone_etv.getText().toString().trim();
        if (!RegexUtils.checkMobile(mobile) && !RegexUtils.checkPhone(mobile)) {
            TUtil.showShort(this, R.string.mobile_erro);
            return;
        }
        if (!isAgreement) {
            TUtil.showShort(this, R.string.agreement_erro);
            return;
        }

        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            httpOperator.requstApplyOpenShop(httpUtil, userId, cityId, shopName,
                    detailAddr, mobile, contact, requestApplyOpenShopHandler);
        } else {
            TUtil.showShort(this, R.string.no_network);
        }
    }


    //获取申请开店回调
    AsyncHttpResponseHandler requestApplyOpenShopHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestApplyOpenShopHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        changeToApplying();
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }finally {
                    dissLoadingDialog();
                }
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };

    //将申请状态变为申请中
    void changeToApplying() {
        unapply_rl.setVisibility(View.GONE);
        apply_rl.setVisibility(View.VISIBLE);
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.mipmap.applying);
        apply_status_iv.setImageBitmap(bitmap);
        apply_status_tv.setText(R.string.applying);
        apply_status_hint_tv.setText(R.string.applying_hint);
        btn.setText(R.string.phone_customer_service);
    }


    //拨打客服电话
    void callService() {
        String servicePhone = "111111";
        Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + servicePhone));
        startActivity(phoneIntent);
    }

    //重新申请
    void applyAgain() {
        unapply_rl.setVisibility(View.VISIBLE);
        apply_rl.setVisibility(View.GONE);
    }

    @Click({R.id.app_common_header_left_icon_iv, R.id.agreement_iv,
            R.id.apply_open_shop_btn, R.id.ask_apply_status_btn,
            R.id.read_agreement_tv

    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.agreement_iv:
                isAgreement = !isAgreement;
                agreement_iv.setSelected(isAgreement);
                break;
            case R.id.apply_open_shop_btn:
                applyOpenShop();
                break;
            case R.id.ask_apply_status_btn:
                if (shopStatus == 0) {
                    callService();
                } else if (shopStatus == 2) {
                    applyAgain();
                }
                break;
            case R.id.read_agreement_tv:
                ProtocolActivity_.intent(this).start();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (helper != null) {
            OpenHelperManager.releaseHelper();
            helper = null;
        }
    }
}
